package com.haiyou.common.util.log;

import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson2.JSONObject;
import com.haiyou.common.spring.schedule.RunnableScheduledTask;
import com.haiyou.common.spring.schedule.ScheduledExecutor;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Getter
@Setter
@ToString
public class LogCounter {

	/**
	 * 限制数量
	 */
	public static final int limit_times = 3;
	
	/**
	 * 间隔时间
	 */
	public static final long limit_time = 1l * 60l * 60l * 1000l;
	//public static final long limit_time = 10l * 1000l;

	
	/**
	 * key
	 */
	private String key;
	
	/**
	 * 创建时间
	 */
	private long time;
	
	/**
	 * 次数
	 */
	private int times;
	
	public void addTimes() {
		
		if(time != 0) {
			return ;
		}
		
		times++;
		
		if(times > limit_times) {
			time = System.currentTimeMillis();
		}
	}
	
	/**
	 * 是否需要限制
	 * @return
	 */
	public boolean limit() {
		
		//没有限制时间
		if(time == 0) {
			return false;
		}
		
		if(time + limit_time <= System.currentTimeMillis()) {
			//不需要限制
			time = 0;
			times = 0;
			return false;
		}
		
		return true;
	}
	
	public static void main(String[] args) {
		
		
		LogCounter counter = new LogCounter();
		
		ScheduledExecutor.getInstance().scheduleWithFixedDelay(new RunnableScheduledTask() {
			@Override
			protected void exec() throws Exception {
				counter.addTimes();
				log.info(String.valueOf(counter.limit()));
				log.info(JSONObject.toJSONString(counter));
			}
		}, 1, 1, TimeUnit.SECONDS);
		
	}
	
	
}
